package com.v.im.authservice.controller;

import com.alibaba.fastjson.JSONObject;
import com.v.im.authservice.constants.RedisKeyConstant;
import com.v.im.businessapi.dto.resultDTO.ImUserResultDTO;
import com.v.im.businessapi.feign.ImUserClientService;
import com.v.im.commonmodule.utils.bean.CurrentUserInfo;
import com.v.im.commonmodule.utils.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Slf4j
@RestController
@RequestMapping("/oauth")
public class UserController {


    @Autowired
    @Qualifier("consumerTokenServices")
    ConsumerTokenServices consumerTokenServices;

    @Resource
    private ImUserClientService imUserClientService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/user")
    public CurrentUserInfo getUserInfo(Principal principal, HttpServletRequest request) {
        String access_token = request.getParameter("access_token");
        CurrentUserInfo userInfo = new CurrentUserInfo();
        String redisKey = RedisKeyConstant.USER_TOKEN_KEY + access_token;
        ImUserResultDTO imUserResultDTO;
        String redisJson = stringRedisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isBlank(redisJson)) {
            imUserResultDTO = imUserClientService.getImUserByUserName(principal.getName());
            stringRedisTemplate.opsForValue().set(redisKey,JSONObject.toJSONString(imUserResultDTO),10000);
        }else{
            System.out.println(redisJson);
            imUserResultDTO = JSONObject.parseObject(redisJson, ImUserResultDTO.class);
        }
        userInfo.setUserId(imUserResultDTO.getId());
        userInfo.setUserName(imUserResultDTO.getName());
        return userInfo;
    }

    @DeleteMapping("/logout")
    public String revokeToken(String access_token) {
        if (consumerTokenServices.revokeToken(access_token)){
            return "注销成功";
        }else{
            return "注销失败";
        }
    }
}